//
//  fwfweew_Tool.m
//  kratos_framework_Example
//
//  Created by 7yao.top on 2018/10/24.
//  Copyright © 2018年 kratos_framework. All rights reserved.
//

#import "fwfweew_Tool.h"
#import <CoreText/CTStringAttributes.h>
#import "sys/utsname.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <Photos/PHPhotoLibrary.h>
#import <Photos/PHAssetCollectionChangeRequest.h>
#import <Photos/PHAssetChangeRequest.h>
#import <Photos/PHCollection.h>
#import "k_const.h"


@interface fwfweew_Tool()
@end

@implementation fwfweew_Tool


+(NSMutableAttributedString *)Kratos_changeCorlorWithColor:(UIColor *)color Kratos_TotalString:(NSString *)totalStr SubStringArray:(NSArray *)subArray {
    NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:totalStr];
    for (NSString *rangeStr in subArray) {
        NSRange range = [totalStr rangeOfString:rangeStr options:NSBackwardsSearch];
        [attributedStr addAttribute:NSForegroundColorAttributeName value:color range:range];
    }
    return attributedStr;
}

+ (NSMutableAttributedString *)Kratos_changeSpaceWithTotalString:(NSString *)totalString Kratos_Space:(CGFloat)space {
    NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:totalString];
    long number = space;
    CFNumberRef num = CFNumberCreate(kCFAllocatorDefault,kCFNumberSInt8Type,&number);
    [attributedStr addAttribute:(id)kCTKernAttributeName value:(__bridge id)num range:NSMakeRange(0,[attributedStr length])];
    CFRelease(num);
    return attributedStr;
}

+ (NSMutableAttributedString *)Kratos_changeFontAndColor:(UIFont *)font Kratos_Color:(UIColor *)color  Kratos_Space:(CGFloat)space  Kratos_TotalString:(NSString *)totalString Kratos_SubStringArray:(NSArray *)subArray {
    NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:totalString];
    for (NSString *rangeStr in subArray) {
        NSRange range = [totalString rangeOfString:rangeStr options:NSBackwardsSearch];
        [attributedStr addAttribute:NSForegroundColorAttributeName value:color range:range];
        [attributedStr addAttribute:NSFontAttributeName value:font range:range];
    }
    
    if (space > 0 )
    {
        
        NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        [paragraphStyle setLineSpacing:space];
        [attributedStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [totalString length])];

    }
    return attributedStr;
}

+ (NSMutableAttributedString *)ls_changeLineSpaceWithTotalString:(NSString *)totalString LineSpace:(CGFloat)lineSpace {
    NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:totalString];
    NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:lineSpace];
    [attributedStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [totalString length])];
    return attributedStr;
}
+ (BOOL)Kratos_valiMobile:(NSString *)mobile
{
    mobile = [mobile stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (mobile.length != 11)
    {
        return NO;
    }else{
        /**
         * 移动号段正则表达式
         */
        NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
        /**
         * 联通号段正则表达式
         */
        NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
        /**
         * 电信号段正则表达式
         */
        NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
        NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
        BOOL isMatch1 = [pred1 evaluateWithObject:mobile];
        NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
        BOOL isMatch2 = [pred2 evaluateWithObject:mobile];
        NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
        BOOL isMatch3 = [pred3 evaluateWithObject:mobile];
        
        if (isMatch1 || isMatch2 || isMatch3) {
            return YES;
        }else{
            return NO;
        }
    }
}


+ (NSArray *)Kratos_matchString:(NSString *)string Kratos_toRegexString:(NSString *)regexStr
{
    
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexStr options:NSRegularExpressionCaseInsensitive error:nil];
    
    NSArray * matches = [regex matchesInString:string options:0 range:NSMakeRange(0, [string length])];
    
    //match: 所有匹配到的字符,根据() 包含级
    
    NSMutableArray *array = [NSMutableArray array];
    
    for (NSTextCheckingResult *match in matches) {
        
        for (int i = 0; i < [match numberOfRanges]; i++) {
            //以正则中的(),划分成不同的匹配部分
            NSString *component = [string substringWithRange:[match rangeAtIndex:i]];
            
            [array addObject:component];
            
        }
        
    }
    
    return array;
    
}



#pragma mark - 当前时间字符串
+ (NSString *)Kratos_currentDateStr{
    NSDate *currentDate = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM"];
    NSString *dateString = [dateFormatter stringFromDate:currentDate];
    return dateString;
}


static NSDateFormatter *cachedDateFormatter = nil;


+ (NSDateFormatter *)cachedDateFormatter {
    
    
    if (!cachedDateFormatter) {
        
        cachedDateFormatter = [[NSDateFormatter alloc] init];
        
        [cachedDateFormatter setDateStyle:NSDateFormatterMediumStyle];
        [cachedDateFormatter setTimeStyle:NSDateFormatterShortStyle];
        [cachedDateFormatter setDateFormat: @"YYYY-MM-dd HH:mm:ss"];
        
    }
    
    return cachedDateFormatter;
    
}


+ (NSString *)Kratos_getTimestamp
{
  
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [cachedDateFormatter setTimeZone:timeZone];
    NSDate *datenow = [NSDate date];
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]];
    return timeSp;
}

+ (void)requestPhoto
{
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
        
    }];
}
+ (void)Kratos_checkPhotoStauts:(void(^)(PHAuthorizationStatus photoAuthorStatus))status
{
    PHAuthorizationStatus photoAuthorStatus = [PHPhotoLibrary authorizationStatus];
    status(photoAuthorStatus);
   
}
+ (void)Kratos_getScreenImageWithView:(UIView *)view Kratos_completionHandle:(void (^)(NSError *error, NSString *localIdentifier))completionHandler
{
    UIGraphicsBeginImageContext(view.bounds.size);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
     PHPhotoLibrary *lib = [PHPhotoLibrary sharedPhotoLibrary];
    __block NSString *localIdentifier = kAlbumName;
    [lib performChanges:^{
        
        // 2.1 创建一个相册变动请求
        PHAssetCollectionChangeRequest *collectionRequest = [self getCurrentPhotoCollectionWithAlbumName:kAlbumName];
        
        // 2.2 根据传入的照片，创建照片变动请求
        PHAssetChangeRequest *assetRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:image];
        
        // 2.3 创建一个占位对象
        PHObjectPlaceholder *placeholder = [assetRequest placeholderForCreatedAsset];
        localIdentifier = placeholder.localIdentifier;
        
        // 2.4 将占位对象添加到相册请求中
        [collectionRequest addAssets:@[placeholder]];
        
   
        
    } completionHandler:^(BOOL success, NSError * _Nullable error) {
        if (error) {
            completionHandler(error, nil);
        } else {
            completionHandler(nil, localIdentifier);
        }
    }];
    

}

+ (PHAssetCollectionChangeRequest *)getCurrentPhotoCollectionWithAlbumName:(NSString *)albumName {
    // 1. 创建搜索集合
    PHFetchResult *result = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    
    // 2. 遍历搜索集合并取出对应的相册，返回当前的相册changeRequest
    for (PHAssetCollection *assetCollection in result) {
        if ([assetCollection.localizedTitle containsString:albumName]) {
            PHAssetCollectionChangeRequest *collectionRuquest = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:assetCollection];
            return collectionRuquest;
        }
    }
    
    // 3. 如果不存在，创建一个名字为albumName的相册changeRequest
    PHAssetCollectionChangeRequest *collectionRequest = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:albumName];
    return collectionRequest;
}



+ (NSString *)getAppleIFA
{
    NSString *ifa = nil;
    Class ASIdentifierManagerClass = NSClassFromString(@"ASIdentifierManager");
    if (ASIdentifierManagerClass) { // a dynamic way of checking if AdSupport.framework is available
        SEL sharedManagerSelector = NSSelectorFromString(@"sharedManager");
        id sharedManager = ((id (*)(id, SEL))[ASIdentifierManagerClass methodForSelector:sharedManagerSelector])(ASIdentifierManagerClass, sharedManagerSelector);
        SEL advertisingIdentifierSelector = NSSelectorFromString(@"advertisingIdentifier");
        NSUUID *advertisingIdentifier = ((NSUUID* (*)(id, SEL))[sharedManager methodForSelector:advertisingIdentifierSelector])(sharedManager, advertisingIdentifierSelector);
        ifa = [advertisingIdentifier UUIDString];
    }
    return ifa;
}

+(NSString *)Kratos_getDeviceName_Kratos
{
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString *deviceModel = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
    //iPhone 系列
    if ([deviceModel isEqualToString:@"iPhone3,1"])    return @"iPhone_4";
    if ([deviceModel isEqualToString:@"iPhone3,2"])    return @"iPhone_4";
    if ([deviceModel isEqualToString:@"iPhone3,3"])    return @"iPhone_4";
    if ([deviceModel isEqualToString:@"iPhone4,1"])    return @"iPhone_4s";
    if ([deviceModel isEqualToString:@"iPhone5,1"])    return @"iPhone_5";
    if ([deviceModel isEqualToString:@"iPhone5,2"])    return @"iPhone_5";
    if ([deviceModel isEqualToString:@"iPhone5,3"])    return @"iPhone_5c";
    if ([deviceModel isEqualToString:@"iPhone5,4"])    return @"iPhone_5c";
    if ([deviceModel isEqualToString:@"iPhone6,1"])    return @"iPhone_5s";
    if ([deviceModel isEqualToString:@"iPhone6,2"])    return @"iPhone_5s";
    if ([deviceModel isEqualToString:@"iPhone7,1"])    return @"iPhone_6_Plus";
    if ([deviceModel isEqualToString:@"iPhone7,2"])    return @"iPhone_6";
    if ([deviceModel isEqualToString:@"iPhone8,1"])    return @"iPhone_6s";
    if ([deviceModel isEqualToString:@"iPhone8,2"])    return @"iPhone_6s_Plus";
    if ([deviceModel isEqualToString:@"iPhone8,4"])    return @"iPhone_SE";
    if ([deviceModel isEqualToString:@"iPhone9,1"])    return @"iPhone_7";
    if ([deviceModel isEqualToString:@"iPhone9,3"])    return @"iPhone_7";
    if ([deviceModel isEqualToString:@"iPhone9,2"])    return @"iPhone_7_Plus";
    if ([deviceModel isEqualToString:@"iPhone9,4"])    return @"iPhone_7_Plus";
    if ([deviceModel isEqualToString:@"iPhone10,1"])    return @"iPhone_8";
    if ([deviceModel isEqualToString:@"iPhone10,4"])    return @"iPhone_8";
    if ([deviceModel isEqualToString:@"iPhone10,2"])    return @"iPhone_8_Plus";
    if ([deviceModel isEqualToString:@"iPhone10,5"])    return @"iPhone_8_Plus";
    if ([deviceModel isEqualToString:@"iPhone10,3"])    return @"iPhone_X";
    if ([deviceModel isEqualToString:@"iPhone10,6"])    return @"iPhone_X";
    if ([deviceModel isEqualToString:@"iPhone11,8"])    return @"iPhone XR";
    if ([deviceModel isEqualToString:@"iPhone11,2"])    return @"iPhone XS";
    if ([deviceModel isEqualToString:@"iPhone11,4"] || [deviceModel isEqualToString:@"iPhone11,6"]) return @"iPhone XS Max";
    
    
    //iPod 系列
    if ([deviceModel isEqualToString:@"iPod1,1"])      return @"iPod_Touch_1";
    if ([deviceModel isEqualToString:@"iPod2,1"])      return @"iPod_Touch_2";
    if ([deviceModel isEqualToString:@"iPod3,1"])      return @"iPod_Touch_3";
    if ([deviceModel isEqualToString:@"iPod4,1"])      return @"iPod_Touch_4";
    if ([deviceModel isEqualToString:@"iPod5,1"])      return @"iPod_Touch";
    if ([deviceModel isEqualToString:@"iPod7,1"])      return @"iPod_Touch_6";
    
    //iPad 系列
    if ([deviceModel isEqualToString:@"iPad1,1"])      return @"iPad";
    if ([deviceModel isEqualToString:@"iPad1,2"])      return @"iPad_3G";
    if ([deviceModel isEqualToString:@"iPad2,1"])      return @"iPad_2";
    if ([deviceModel isEqualToString:@"iPad2,2"])      return @"iPad_2";
    if ([deviceModel isEqualToString:@"iPad2,3"])      return @"iPad_2";
    if ([deviceModel isEqualToString:@"iPad2,4"])      return @"iPad_2";
    if ([deviceModel isEqualToString:@"iPad2,5"])      return @"iPad_Mini";
    if ([deviceModel isEqualToString:@"iPad2,6"])      return @"iPad_Mini";
    if ([deviceModel isEqualToString:@"iPad2,7"])      return @"iPad_Mini";
    
    if ([deviceModel isEqualToString:@"iPad3,1"])      return @"iPad_3";
    if ([deviceModel isEqualToString:@"iPad3,2"])      return @"iPad_3";
    if ([deviceModel isEqualToString:@"iPad3,3"])      return @"iPad_3";
    if ([deviceModel isEqualToString:@"iPad3,4"])      return @"iPad_4";
    if ([deviceModel isEqualToString:@"iPad3,5"])      return @"iPad_4";
    if ([deviceModel isEqualToString:@"iPad3,6"])      return @"iPad_4";
    
    if ([deviceModel isEqualToString:@"iPad4,1"])      return @"iPad_Air";
    if ([deviceModel isEqualToString:@"iPad4,2"])      return @"iPad_Air";
    if ([deviceModel isEqualToString:@"iPad4,3"])      return @"iPad_Air";
    if ([deviceModel isEqualToString:@"iPad5,1"])      return @"iPad_Mini_4";
    if ([deviceModel isEqualToString:@"iPad5,2"])      return @"iPad_Mini_4";
    if ([deviceModel isEqualToString:@"iPad5,3"])      return @"iPad_Air_2";
    if ([deviceModel isEqualToString:@"iPad5,4"])      return @"iPad_Air_2";
    
    if ([deviceModel isEqualToString:@"iPad6,3"])      return @"iPad_Pro_9.7";
    if ([deviceModel isEqualToString:@"iPad6,4"])      return @"iPad_Pro_9.7";
    if ([deviceModel isEqualToString:@"iPad6,7"])      return @"iPad_Pro_12.9";
    if ([deviceModel isEqualToString:@"iPad6,8"])      return @"iPad_Pro_12.9";
    if ([deviceModel isEqualToString:@"AppleTV2,1"])      return @"Apple_TV_2";
    if ([deviceModel isEqualToString:@"AppleTV3,1"])      return @"Apple_TV_3";
    if ([deviceModel isEqualToString:@"AppleTV3,2"])      return @"Apple_TV_3";
    if ([deviceModel isEqualToString:@"AppleTV5,3"])      return @"Apple_TV_4";
    
    if ([deviceModel isEqualToString:@"i386"])         return @"Simulator";
    if ([deviceModel isEqualToString:@"x86_64"])       return @"Simulator";
    
    if ([deviceModel isEqualToString:@"iPad4,4"]
        ||[deviceModel isEqualToString:@"iPad4,5"]
        ||[deviceModel isEqualToString:@"iPad4,6"])      return @"iPad_Mini_2";
    
    if ([deviceModel isEqualToString:@"iPad4,7"]
        ||[deviceModel isEqualToString:@"iPad4,8"]
        ||[deviceModel isEqualToString:@"iPad4,9"])      return @"iPad_Mini_3";
    
    
    return deviceModel;
}
@end
